package news.newstopic.controller;

import com.alibaba.fastjson.JSON;
import news.newstopic.entity.NewsTopic;
import news.newstopic.service.AddTopicServiceImpl;
import news.newstopic.service.IAddTopicService;
import news.util.BaseHttpServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


/**
 * @author Administrator
 * 添加主题
 */
@WebServlet("/TopicController")
public class AddTopicController extends BaseHttpServlet {
    private IAddTopicService iAddTopicService = new AddTopicServiceImpl();
    private static final long serialVersionUID = 1L;
    /**
     * @Author GongXL
     * @Description  获得主题列表
     * @Date 14:42 2022/3/3
     * @Param [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse]
     * @return void
     **/
    public void getNewsTopicList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        //要返回什么数据
        //TODO 查询主题信息，所有主题构成json返回
        List<NewsTopic> newsTopicList = iAddTopicService.getNewsTopicList();
//        JSON
        String resJson = JSON.toJSONString(newsTopicList);
        writer.write(resJson);
        writer.flush();
        writer.close();


    }
    /**
     * @Author GongXL
     * @Description  添加主题
     * @Date 14:41 2022/3/3
     * @Param [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse]
     * @return void
     **/
    public void addTopic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");
        //1.接受参数
        //2.存储数据
        String topicName = request.getParameter("topicName");

        iAddTopicService.addTopic(topicName);

        //3.返回成功响应

        request.getRequestDispatcher(request.getContextPath()+"/news/suc.jsp").forward(request,response);
    }

}